package com.ming.springboot.security;

import com.alibaba.fastjson.JSON;
import com.ming.springboot.data.Result;
import com.ming.springboot.data.ResultCode;
import com.ming.springboot.util.JwtTokenUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by mqsi on 2022/5/24 16:35
 */
@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		Result result = Result.success(ResultCode.LOGIN_SUCCESS.getCode(), "Login success");
		// 获取授权中的用户信息
		SelfUserDetails userDetails = (SelfUserDetails) authentication.getPrincipal();
		// 对用户进行加密生成Token字符串
		String jwtToken = JwtTokenUtil.generateToken(userDetails.getUsername(), 300, "_secret");
		// 将Token字符串保存到消息实体中
		result.setJwtToken(jwtToken);
		response.getWriter().write(JSON.toJSONString(result));
	}
}
